import {
  addChannelAPI,
  delChannelAPI,
  getAllChannel,
  getUserChannel,
} from '@/api/channel';
import { getChannel, hasToken, setChannel } from '@/utils/local';
import { AppDispatch } from '..';
import { ChannelListType } from '../reducer/channel';

export const getAllChgannelAction = () => {
  return async (dispatch: AppDispatch) => {
    const res = await getAllChannel();
    dispatch({
      type: 'channel/getAllChannel',
      payload: res.data.channels,
    });
  };
};
export const getUserChgannelAction = () => {
  return async (dispatch: AppDispatch) => {
    if (hasToken()) {
      const res = await getUserChannel();
      dispatch({
        type: 'channel/getUserChgannel',
        payload: res.data.channels,
      });
      return;
    }
    //没登录情况 , 用缓存
    let localChannel = getChannel();
    if (localChannel.length === 0) {
      // 如果缓存没有数据 , 重新请求
      const res = await getAllChannel();
      localChannel = res.data.channels.splice(0, 10);
      setChannel(localChannel);
    }

    dispatch({
      type: 'channel/getUserChgannel',
      payload: localChannel,
    });
  };
};
export const addChannelAction = (data: ChannelListType) => {
  return async (dispatch: AppDispatch) => {
    if (hasToken()) {
      await addChannelAPI({ channels: [data] });
      dispatch({
        type: 'channel/AddChgannel',
        payload: data,
      });
      return;
    }
    //没登录情况 , 用缓存
    const newChannel = getChannel();
    setChannel([...newChannel, data]);
    dispatch({
      type: 'channel/AddChgannel',
      payload: data,
    });
  };
};
export const delChannelAction = (id: number) => {
  return async (dispatch: AppDispatch) => {
    if (hasToken()) {
      await delChannelAPI(id);
      dispatch({
        type: 'channel/delChannel',
        payload: id,
      });
      return;
    }
    //没登录情况 , 用缓存
    const newChannel = getChannel();
    setChannel(newChannel.filter((item) => item.id !== id));
    dispatch({
      type: 'channel/delChannel',
      payload: id,
    });
  };
};
